<template>
  <div class="news-detail-page">
    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-container" vertical>
      加载中...
    </van-loading>

    <!-- 新闻内容 -->
    <div v-else class="news-content">
      <!-- 新闻标题 -->
      <h1 class="news-title">{{ newsDetail.title }}</h1>
      
      <!-- 新闻信息 -->
      <div class="news-meta">
        <span class="publish-time">{{ formatTime(newsDetail.pub_time || newsDetail.pubTime || newsDetail.publishTime) }}</span>
        <span class="category">{{ newsDetail.category }}</span>
        <span v-if="newsDetail.section" class="section">{{ newsDetail.section }}</span>
      </div>

      <!-- 新闻正文 -->
      <div v-if="newsDetail.content_html || newsDetail.contentHtml || newsDetail.content"
           class="news-body"
           v-html="newsDetail.content_html || newsDetail.contentHtml || newsDetail.content">
      </div>
      <div v-else class="no-content">
        <p>暂无文章内容</p>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <van-button
          :icon="isFavorited ? 'star' : 'star-o'"
          :type="isFavorited ? 'primary' : 'default'"
          size="small"
          @click="toggleFavorite"
        >
          {{ isFavorited ? '已收藏' : '收藏' }}
        </van-button>
        
        <van-button
          icon="share-o"
          type="default"
          size="small"
          @click="shareNews"
        >
          分享
        </van-button>
      </div>
    </div>

    <!-- 相关新闻 -->
    <div v-if="relatedNews.length > 0" class="related-news">
      <h3 class="section-title">相关新闻</h3>
      <van-cell
        v-for="item in relatedNews"
        :key="item.news_id || item.newsId || item.id"
        :title="item.title"
        :label="formatTime(item.pub_time || item.pubTime || item.publishTime)"
        is-link
        @click="goToNews(item.news_id || item.newsId || item.id)"
      />
    </div>

    <!-- 分享面板 -->
    <van-share-sheet
      v-model:show="showShareSheet"
      title="立即分享给好友"
      :options="shareOptions"
      @select="onShareSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Loading, Button, Cell, ShareSheet, showToast } from 'vant'
import { articleApi } from '../utils/api'
import { useFavoritesStore } from '../stores/favorites'
import { useNewsStore } from '../stores/news'
import { useHistoryStore } from '../stores/history'
import { formatDate as formatTime } from '../utils/dateUtils'

const router = useRouter()
const route = useRoute()
const favoritesStore = useFavoritesStore()
const newsStore = useNewsStore()
const historyStore = useHistoryStore()

// 获取路由参数
const newsId = route.params.id

// 响应式数据
const loading = ref(true)
const newsDetail = ref({})
const relatedNews = ref([])
const isFavorited = computed(() => favoritesStore.isFavorited(newsId))
const showShareSheet = ref(false)

// 分享选项
const shareOptions = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: 'QQ', icon: 'qq' },
  { name: '复制链接', icon: 'link' },
]

// 处理HTML内容，移除特定格式的文本
const processHtmlContent = (html) => {
  if (!html) return ''

  console.log('原始HTML内容长度:', html.length)

  // 直接使用宽松模式匹配所有包含text-align:center;text-indent:2em的段落
  const pattern = /<p\s+style="[^"]*text-align:center;\s*text-indent:2em;[^"]*">.*?<\/p>/g

  const beforeLength = html.length
  const processedHtml = html.replace(pattern, (match) => {
    console.log('替换格式:', match)
    return ''
  })

  if (beforeLength !== processedHtml.length) {
    console.log('替换成功，替换前长度:', beforeLength, '替换后长度:', processedHtml.length)
  } else {
    console.log('未找到匹配内容，HTML未变化')
  }

  return processedHtml
}

// 时间格式化函数已移至 @/utils/dateUtils.js

// 获取新闻详情
const fetchNewsDetail = async () => {
  try {
    loading.value = true

    // 使用Pinia store获取新闻详情
    const result = await newsStore.getNewsDetail(articleApi, newsId)

    if (result.success) {
      newsDetail.value = result.data
      console.log('获取新闻详情成功:', newsDetail.value.title)

      // 如果获取到了文章数据，处理HTML内容
      if (newsDetail.value && newsDetail.value.content_html) {
        newsDetail.value.content_html = processHtmlContent(newsDetail.value.content_html)
      }

      // 添加到浏览历史
      historyStore.addHistory(newsDetail.value)

      // 获取相关新闻
      await fetchRelatedNews()

      // 检查是否已收藏
      checkFavoriteStatus()
    } else {
      console.error('获取新闻详情失败:', result.error)
      showToast('加载失败，请重试')
    }

  } catch (error) {
    console.error('获取新闻详情失败:', error)
    showToast('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取相关新闻
const fetchRelatedNews = async () => {
  try {
    // 获取最新5篇文章作为相关新闻
    const result = await articleApi.getArticleList({ limit: 5, page: 1 })

    let articles = []

    if (result && result.code === 200 && result.data) {
      if (Array.isArray(result.data)) {
        articles = result.data
      } else if (result.data.list && Array.isArray(result.data.list)) {
        articles = result.data.list
      }
    } else if (Array.isArray(result)) {
      articles = result
    } else if (result && result.list && Array.isArray(result.list)) {
      articles = result.list
    }

    // 过滤掉当前文章，只显示其他文章
    relatedNews.value = articles
      .filter(article => (article.news_id || article.newsId || article.id) !== newsId)
      .slice(0, 4) // 最多显示4篇相关新闻

  } catch (error) {
    console.error('获取相关新闻失败:', error)
    relatedNews.value = []
  }
}

// 检查收藏状态
const checkFavoriteStatus = () => {
  // 使用Pinia store检查收藏状态
  // isFavorited已经是响应式的，会自动更新
}

// 切换收藏状态
const toggleFavorite = async () => {
  try {
    const result = await favoritesStore.toggleFavorite(newsId)

    if (result.action === 'added') {
      showToast('已添加到收藏')
    } else {
      showToast('已取消收藏')
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    showToast('操作失败，请重试')
  }
}

// 分享新闻
const shareNews = () => {
  showShareSheet.value = true
}

// 处理分享选择
const onShareSelect = (option) => {
  showToast(`分享到${option.name}`)
  showShareSheet.value = false
}

// 跳转到其他新闻
const goToNews = (id) => {
  router.push({ name: 'news-detail', params: { id } })
}

// 滚动到顶部
const scrollToTop = () => {
  window.scrollTo(0, 0)
}

// 页面加载时获取数据
onMounted(() => {
  fetchNewsDetail()
  scrollToTop()
})
</script>

<style scoped>
.news-detail-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.news-content {
  background: white;
  padding: 20px 16px;
  margin-bottom: 8px;
}

.news-title {
  font-size: 20px;
  font-weight: 600;
  line-height: 1.4;
  color: #323233;
  margin: 0 0 12px 0;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebedf0;
  margin-bottom: 16px;
}

.publish-time {
  font-size: 14px;
  color: #969799;
}

.category {
  font-size: 12px;
  color: #1989fa;
  background: #e8f3ff;
  padding: 2px 8px;
  border-radius: 12px;
}

.section {
  font-size: 12px;
  color: #ff976a;
  background: #fff7f0;
  padding: 2px 8px;
  border-radius: 12px;
}

.news-body {
  line-height: 1.6;
  color: #323233;
  font-size: 16px;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.news-body :deep(p) {
  margin: 12px 0;
  text-align: justify;
}

.news-body :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  display: block;
  margin: 12px auto;
}

.news-body :deep(h1),
.news-body :deep(h2),
.news-body :deep(h3),
.news-body :deep(h4),
.news-body :deep(h5),
.news-body :deep(h6) {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.4;
}

.news-body :deep(ul),
.news-body :deep(ol) {
  margin: 12px 0;
  padding-left: 20px;
}

.news-body :deep(li) {
  margin: 4px 0;
}

.news-body :deep(blockquote) {
  margin: 16px 0;
  padding: 12px 16px;
  background-color: #f7f8fa;
  border-left: 4px solid #1989fa;
  border-radius: 4px;
}

.news-body :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 14px;
}

.news-body :deep(th),
.news-body :deep(td) {
  border: 1px solid #ebedf0;
  padding: 8px 12px;
  text-align: left;
}

.news-body :deep(th) {
  background-color: #f7f8fa;
  font-weight: 600;
}

.no-content {
  text-align: center;
  padding: 40px 20px;
  color: #969799;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebedf0;
}

.related-news {
  background: white;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  padding: 16px 16px 8px;
  margin: 0;
}
</style>
